package com.yuanqiworld.vw.domain;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import sun.misc.Regexp;

@RooJavaBean
@RooToString
@RooJson
@RooJpaActiveRecord(table = "vw_user", finders = {"findUserInfoesByUsername", "findUserInfoesByEmail"})
public class UserInfo {

    @Autowired
    private transient PasswordEncoder passwordEncoder;

    @NotNull
    @Column(unique = true)
    private String username;

    private String password;

    @NotNull
    private String realName;

    @Pattern(regexp = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$")
    public String email;

    private boolean enabled = true;

    @Transient
    private String oldPassword;

    @Transient
    private String confirmPassword;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "vw_user_role",
            joinColumns = {@javax.persistence.JoinColumn(name = "user_id")},
            inverseJoinColumns = {@javax.persistence.JoinColumn(name = "role_id")})
    private Set<RoleInfo> roles = new HashSet<RoleInfo>();

    public void encodePassword() {
        this.password = passwordEncoder.encodePassword(password, null);
    }

    public static boolean isPasswordValid(String encPass, String rawPass) {
        return passwordEncoder().isPasswordValid(encPass, rawPass, null);
    }

    private static PasswordEncoder passwordEncoder() {
        return new UserInfo().passwordEncoder;
    }

    public String randomPassword() {
        String password = RandomStringUtils.random(6, "0123456789");
        setPassword(password);
        encodePassword();
        return password;
    }
}
